<?php

namespace App\Config;

class Config
{

    protected $config = [
      'app' => [
          'name' => 'code'
      ],
       'db' => [
           'host' => '127.0.0.1',
           'database' => 'autowiring',
           'username' => 'root',
           'password' => 'password',
       ]
    ];

    protected $cache = [];

    function __construct()
    {
        dump(123);
    }


    public function get($key, $default = null)
    {
        if ($this->existsInCache($key)) {
            return $this->fromCache($key);
        }

        return $this->addToCache(
            $key, $this->extractFromConfig($key) ?? $default
        );
    }

    public function extractFromConfig($key)
    {
        $keys = explode('.', $key);
        return $this->config[$keys[0]][$keys[1]];
    }

    public function addToCache($key, $default)
    {
        $keys = explode('.', $key);
        $this->cache[$keys[0]][$keys[1]] = $default;
        return $this->cache[$keys[0]][$keys[1]];
    }

    public function fromCache($key)
    {
        if (count(explode('.', $key))) {
            return $this->cache[explode('.', $key)[0]][[explode('.', $key)][1]];
        }
        return $this->cache[$key];
    }

    public function existsInCache($key)
    {
        if (count(explode('.', $key)) > 1) {
            return isset($this->cache[explode('.', $key)[0]]);
        }
        return isset($this->cache[$key]);
    }


    public function config()
    {
        var_dump('config');
    }

    public function cache()
    {
        var_dump('cache');
    }
}